package sgi.client;

import java.io.IOException;

import javax.swing.SwingUtilities;

import sgi.message.MessageApproveTariff;
import sgi.message.MessageRetrieveTariff;


public class SGICEOTariffController extends SGIController{

	
	private static SGICEOTariffController tariffController;
	private static SGICEOTariffUI tariffUI;
	
	public static SGICEOTariffController create(){
		if(SGICEOTariffController.tariffController == null){
			SGICEOTariffController.tariffController = new SGICEOTariffController();
			SGICEOTariffController.tariffUI.setSgiCEOTariffController(tariffController);
		}
		SGICEOTariffController.tariffUI.setVisible(true);
		return SGICEOTariffController.tariffController; 
	}	
	
	private SGICEOTariffController (){
		SGICEOTariffController.tariffUI = new SGICEOTariffUI();
		requestTariff();
	}
	
	public static void terminate(){
		SGICEOTariffController.tariffUI.setVisible(false);
		SGICEOTariffController.tariffUI = null;
		SGICEOTariffController.tariffController = null;
	}
	
	public static SGICEOTariffUI getUI(){
		return SGICEOTariffController.tariffUI;
	}
		
	private void requestTariff(){
		MessageRetrieveTariff messageRetrieveTariff = new MessageRetrieveTariff(false);
		try {
			SGIClientConnectionController.createConnection().handleMessageFromClientUI(messageRetrieveTariff);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void approveTariff(boolean approved)
	{
		MessageApproveTariff messageApproveTariff = new MessageApproveTariff(approved);
		try {
			SGIClientConnectionController.createConnection().handleMessageFromClientUI(messageApproveTariff);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
	}
	
	@Override
	
	void handleMessage(final Object msg) {
		if(msg instanceof MessageRetrieveTariff)
		{
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					MessageRetrieveTariff messageRetrieveTariff = (MessageRetrieveTariff) msg;
					SGICEOTariffController.tariffUI.loadCurrentTariff(messageRetrieveTariff.getCurrentTariff());
					if(messageRetrieveTariff.hasPendings()){
						SGICEOTariffController.tariffUI.loadPendingTariff(messageRetrieveTariff.getPendingTariff());
					}
				}
			});

		}
			
	}
}
